package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.UserSearchDto;
import com.heima.search.entity.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 关键词联想
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.参数校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.okResult(null);
        }

        //2.获取关键词进行模糊查询
        Query query = Query.query(Criteria.where("associateWords").regex(".*?" + dto.getSearchWords() + ".*")).limit(dto.getPageSize());
        List<ApAssociateWords> list = mongoTemplate.find(query, ApAssociateWords.class);

        return ResponseResult.okResult(list);
    }
}
